from django.shortcuts import render,HttpResponse
from dwebsocket import websocket
from dwebsocket.decorators import accept_websocket,require_websocket
from fis.connectDataBase import ConnectDataBase
import time,json
from django.core.serializers import serialize

# Create your views here.

# accept_websocket-—可以接受websocket请求和普通http请求
# require_websocket----只接受websocket请求,拒绝普通http请求

# request.is_websocket()  #websocket请求返回True,普通请求返回False
# request.websocket  # websocket建立连接后,request将有websocket提供的相关api属性,如果没有建立连接则是None
# WebSocket.wait()  # 阻塞接收消息
# WebSocket.read()  # 非阻塞接收消息
# WebSocket.count_messages()  #返回队列中的消息数量
# WebSocket.has_messages()  # 有消息返回True,反之False
# WebSocket.send(message)  # 发送消息
# WebSocket.__iter__()  # 当迭代器使用
import datetime

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj,datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self,obj)

def getFisInfo(sql):
    cdb = ConnectDataBase()
    result = cdb.selectQuery(sql)
    # print(result)
    return result


def getIndex(request):
    return render(request,'index.html')

@accept_websocket
def sendData(request):
    currDate = str(datetime.date.today()).replace('-','')
    currDate = '20191011'
    sql_fis_m100 = "select PMATERIALNO from fis_M100 where CP5A like  '%"+currDate+"%'"
    #自动发货列表
    sql_auto_send = "select PMATERIALNO,SENDSTATE from fis_M100Send where CP5A like  '%"+currDate+"%'"
    #手动发货哦查询列表
    currDate = '2019-10-11'
    sql_man_send = "SELECT config_Key,sendstate FROM [BC311_Mes].[dbo].[fis_R100SendMan] where Convert(varchar,add_time,120) LIKE '"+currDate+"%'"

    flag = True
    if request.is_websocket():
        while flag:
            #循环把用户发送的所有消息读出来
            while request.websocket.has_messages():
                message = request.websocket.wait()
                print('message:',message.decode())

            #所有配置信息,数据库查询结果
            rows_fis = getFisInfo(sql_fis_m100)
            rows_auto_send = getFisInfo(sql_auto_send)
            rows_man_send = getFisInfo(sql_man_send)

            #fis订单信息
            code_fis_send = getCarModel(rows_fis)
            #自动发货信息
            code_auto_send = getAutoCarSend(rows_auto_send)
            #获取数组中的偶数位置的数据为list[1::2]  奇数位置[::2]
            code_auto_sended = code_auto_send[1::2]
            # print('auto:',code_auto_sended)
            #手动发货信息
            code_man_send = getManCarSend(rows_man_send)
            code_man_sended = code_man_send[1::2]
            print('man',code_man_send)
            print('man',code_man_sended)
            #手动和自动发货汇总
            code_send = [x+y for x,y in zip(code_auto_send,code_man_send)]
            code_sended = code_send[::2]
            #剩余发货信息
            remaining_send = [x-y for x,y in zip(code_fis_send,code_sended)]

            data = {}
            #fis订单需要发货数量
            data['fis_send'] = code_fis_send
            #自动已发数量
            data['auto_sended'] = code_auto_sended
            #手动已发数量
            data['man_sended'] = code_man_sended
            #合计已发数量
            data['code_sended'] = code_sended
            #剩余需要发货数量
            data['remaining_send'] = remaining_send
            # print(data)
            data_json = json.dumps(data,cls=DateEncoder)
            request.websocket.send(data_json)
            time.sleep(10)
    else:
        print('不是websocket请求')

#根据FIS信息的底盘号计算当日各个配置车型的数量
def getCarModel(rows):
    code1, code2, code3, code4 = 0, 0, 0, 0
    for row in rows:
        # 主司机配置
        PMATERIALNO = row['PMATERIALNO']
        # 配置代码
        model = PMATERIALNO[-3:]
        # 配置模式
        model_desc = ''
        model_code = 0
        if (model == 'UQK'):
            model_desc = '基本'
            model_code = 1
            code1 += 1
        elif (model == 'UQL'):
            model_desc = '舒适'
            model_code = 2
            code2 += 1
        elif (model == 'UQM'):
            model_desc = '豪华黑'
            model_code = 3
            code3 += 1
        elif (model == 'UQN'):
            model_code = 4
            model_desc = '豪华红'
            code4 += 1
        # 1基本UQK
        # 2舒适UQL
        # 3豪华黑UQM
        # 4豪华红UQN
    return [code1,code2,code3,code4]

#根据自动发货列表获取已发自动发货的数量
def getAutoCarSend(rows):
    code1,code1_sended, code2,code2_sended, code3,code3_sended, code4,code4_sended \
        = 0, 0, 0, 0, 0, 0, 0, 0
    # print('autosend',rows)
    for row in rows:
        # 主司机配置
        PMATERIALNO = row['PMATERIALNO']
        SENDSTATE = row['SENDSTATE']
        # 配置代码
        model = PMATERIALNO[-3:]
        # 配置模式
        model_desc = ''
        model_code = 0
        if (model == 'UQK'):
            model_desc = '基本'
            model_code = 1
            if(SENDSTATE == True):
                code1_sended += 1
            else:
                code1 += 1
        elif (model == 'UQL'):
            model_desc = '舒适'
            model_code = 2
            if (SENDSTATE == True):
                code2_sended += 1
            else:
                code2 += 1
        elif (model == 'UQM'):
            model_desc = '豪华黑'
            model_code = 3
            if (SENDSTATE == True):
                code3_sended += 1
            else:
                code3 += 1
        elif (model == 'UQN'):
            model_code = 4
            model_desc = '豪华红'
            if (SENDSTATE == True):
                code4_sended += 1
            else:
                code4 += 1
        # 1基本UQK
        # 2舒适UQL
        # 3豪华黑UQM
        # 4豪华红UQN
    return [code1,code1_sended,code2,code2_sended,code3,code3_sended,code4,code4_sended]

#根据手动发货列表计算已手动发货的数量
def getManCarSend(rows):
    code1, code1_sended, code2, code2_sended, code3, code3_sended, code4, code4_sended \
        = 0, 0, 0, 0, 0, 0, 0, 0
    # print('mansend',rows)
    for row in rows:
        config_key = row['config_Key']
        sendstate = row['sendstate']
        # print(config_key,sendstate)
        # 配置模式
        model_desc = ''
        model_code = 0
        if (config_key == '1'):
            model_desc = '基本'
            model_code = 1
            if (sendstate == True):
                code1_sended += 1
            else:
                code1 += 1
        elif (config_key == '2'):
            model_desc = '舒适'
            model_code = 2
            if (sendstate == True):
                code2_sended += 1
            else:
                code2 += 1
        elif (config_key == '3'):
            model_desc = '豪华黑'
            model_code = 3
            if (sendstate == True):
                code3_sended += 1
            else:
                code3 += 1
        elif (config_key == '4'):
            model_code = 4
            model_desc = '豪华红'
            if (sendstate == True):
                code4_sended += 1
            else:
                code4 += 1
        # 1基本UQK
        # 2舒适UQL
        # 3豪华黑UQM
        # 4豪华红UQN
    return [code1, code1_sended, code2, code2_sended, code3, code3_sended, code4, code4_sended]